package com.bsoft.apiservice.web;

import com.alibaba.druid.util.StringUtils;
import com.bsoft.apiservice.dto.LabRequisition;
import com.bsoft.apiservice.dto.LabRequisitionMx;
import com.bsoft.apiservice.dto.LabRequisitionRequest;
import com.bsoft.apiservice.dto.LabRequisitionResponse;
import com.bsoft.apiservice.service.LabRequisitionService;
import com.bsoft.apiservice.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;

@RestController
@RequestMapping("/api/labrequisition")
@Slf4j
public class LabRequisitionController {

    @Autowired
    private LabRequisitionService labRequisitionService;
    @Resource
    private JdbcTemplate jdbcTemplate;
 /*   @Resource
    private LabRequisition labRequisition;
    @Resource
    private LabRequisitionMx labRequisitionMx;*/

    @PostMapping("/add")
    public LabRequisitionResponse addLabRequisition(@RequestBody LabRequisitionRequest request) {

        LabRequisition labRequisition = new LabRequisition();
        LabRequisitionMx labRequisitionMx = new LabRequisitionMx();
        String jgid = "";
        log.info("打印入参："+request);
        LabRequisitionResponse response = new LabRequisitionResponse();
        LabRequisitionResponse.MsgHeader header = new LabRequisitionResponse.MsgHeader();
        header.setOrganization(request.getMsgHeader().getOrganization());
        header.setSender(request.getMsgHeader().getSender());
        header.setServiceType(request.getMsgHeader().getServiceType());
        header.setMsgType(request.getMsgHeader().getMsgType());
        header.setMsgVersion(request.getMsgHeader().getMsgVersion());
        response.setMsgHeader(header);
        LabRequisitionResponse.MsgBody body = new LabRequisitionResponse.MsgBody();

        if(request.getMsgBody().getPatient()==null || request.getMsgBody().getVisit()==null || request.getMsgBody().getVisit()==null){
            body.setStatus("false");
            body.setCode("500");
            body.setDetail("入参有误！");
            response.setMsgBody(body);
            return response;
        }
        String organizationId = request.getMsgBody().getVisit().getVisitOrganization();
        if (!StringUtils.isEmpty(organizationId) && !organizationId.equals("null")) {
            String sql_jg = "select JGID,JGMC from v_lis_yljg where JGDM = '" + organizationId + "'";
            log.info(sql_jg);
            List<Map<String, Object>> list_jg = jdbcTemplate.queryForList(sql_jg);
            if (list_jg.size() <= 0) {
                body.setStatus("false");
                body.setCode("500");
                body.setDetail("机构信息验证失败,请核对传入的机构代码！");
                response.setMsgBody(body);
                return response;
            }
            jgid = list_jg.get(0).get("JGID").toString();
            labRequisition.setJgid(jgid);
            log.info("jgid------------------"+jgid);
        }
        String brid = request.getMsgBody().getPatient().getSourcePatientId();//brid
        brid= Tools.removeAllNonAlphaNumeric(brid);
        labRequisition.setBrid(brid);
        String AuthorOrganization = request.getMsgBody().getPatient().getAuthorOrganization();//建档机构代码
        String SourcePatientIdType = request.getMsgBody().getPatient().getSourcePatientIdType();//业务系统患者档案类型
        String cardNumber = request.getMsgBody().getPatient().getIdCard();
        labRequisition.setCardNumber(cardNumber);
        String cardType = request.getMsgBody().getPatient().getIdCardCode();
        String patientName = request.getMsgBody().getPatient().getName();
        labRequisition.setPatientname(patientName);
        String sex = request.getMsgBody().getPatient().getSex();
        labRequisition.setSex(sex);
        String birthday = request.getMsgBody().getPatient().getBirthDate();
        labRequisition.setBirthday(birthday);

        
        String age = "";
        String age_unit = "";
        if (!birthday.equals("")) {
            Map birmap = Tools.ageFormat(Tools.TStrToDate(birthday.toString()), null);
            age = birmap.get("age") + "";
            age_unit = birmap.get("age_unit") + "";
        }
        String PatientProperties = request.getMsgBody().getPatient().getPatientProperties();//病人性质
        if("".equals(PatientProperties) || PatientProperties==null){
            labRequisition.setPatientProperties("自费");//默认自费
        }
        labRequisition.setPatientProperties(PatientProperties);
        String telephone = request.getMsgBody().getPatient().getPatientPhone();
        labRequisition.setTelephone(telephone);
        String address = request.getMsgBody().getPatient().getAddress();
        String source = request.getMsgBody().getVisit().getPatientType();
        String patientMedicalCardNumber = request.getMsgBody().getVisit().getMedicalCardId();
        String patientMedicalCardType = request.getMsgBody().getVisit().getMedicalCardType();
        String ClinicId = request.getMsgBody().getVisit().getClinicId();
        String visitId = request.getMsgBody().getVisit().getVisitId();
        labRequisition.setVisitid(visitId);
        String inHospitalRecordCode = request.getMsgBody().getVisit().getHospizationId();
        String sPatientId="";//病人编号
        String istayhospitalmode = "1";
        Integer isource=Tools.ToInt(source);
        if (source.equals("01") || isource==1) {
            istayhospitalmode = "1";
            sPatientId=ClinicId;
        } else if (source.equals("02") || isource==2) {
            istayhospitalmode = "2";
            sPatientId=patientMedicalCardNumber;
        } else if (source.equals("03") || isource==3) {
            istayhospitalmode = "3";
            sPatientId=patientMedicalCardNumber;
        } else if (source.equals("04") || isource==4) {
            istayhospitalmode = "2";
            sPatientId=inHospitalRecordCode;
        }
        if(StringUtils.isEmpty(sPatientId))
        {
            sPatientId=patientMedicalCardNumber;
        }
        labRequisition.setPatientid(brid);
        labRequisition.setStayhospitalmode(istayhospitalmode);
        if(StringUtils.isEmpty(sPatientId)) {
            body.setStatus("false");
            body.setCode("500");
            body.setDetail("就诊卡号,门（急）诊号,住院号不能全为空");
            response.setMsgBody(body);
            return response;
        }

        // 将请求对象转换为实体对象
        String applicationNo = request.getMsgBody().getLabRequest().getRequestId();
        labRequisition.setApplicationNo(applicationNo);

        String IsNeonatus = request.getMsgBody().getLabRequest().getIsNeonatus();//婴儿标志
        labRequisition.setIsNeonatus(IsNeonatus);
        /***************年龄判断*********************/
        String Age = request.getMsgBody().getLabRequest().getAge();
        String MonthAge = request.getMsgBody().getLabRequest().getMonthAge();//婴儿标志
        /***************年龄判断*********************/
        if (StringUtils.isEmpty(age)) {
            if (!StringUtils.isEmpty(Age) && Tools.ToInt(Age) > 0) {
                age = Age;
                age_unit = "1";
            } else if (!StringUtils.isEmpty(MonthAge) && Tools.ToInt(MonthAge) > 0) {
                age = MonthAge;
                age_unit = "2";
            }
        }
        labRequisition.setAge(age);
        labRequisition.setAge_unit(age_unit);
        String inpatientWardId = request.getMsgBody().getLabRequest().getWardArea();
        labRequisition.setInpatientWardId(inpatientWardId);
        if(inpatientWardId !=null && !"".equals(inpatientWardId)){
            inpatientWardId=Tools.doKsdm(inpatientWardId);
            if (istayhospitalmode == "2" && StringUtils.isEmpty(inpatientWardId)) {
                Integer ijgid = Tools.ToInt(jgid);
                if (!getExistsByKsdm(ijgid, inpatientWardId,jdbcTemplate)) {
                    body.setStatus("false");
                    body.setCode("500");
                    body.setDetail("病人病区代码WardArea 为:" + inpatientWardId + "，在科室表中未找到，请同步科室表信息！");
                    response.setMsgBody(body);
                    return response;
                }
            }
        }

        String SickbedNo = request.getMsgBody().getLabRequest().getSickbedNo();//病床编码
        labRequisition.setSickbedNo(SickbedNo);
        String isEmergency = request.getMsgBody().getLabRequest().getIsEmergency();
        labRequisition.setIsEmergency(isEmergency);
        String applyTime = request.getMsgBody().getLabRequest().getRequestDateTime();
        labRequisition.setApplyTime(applyTime);
        String applyDoctorId = request.getMsgBody().getLabRequest().getRequestDoctor();
        labRequisition.setApplyDoctorId(applyDoctorId);
        //申请医生代码校验
        if (StringUtils.isEmpty(applyDoctorId))
        {
            body.setStatus("false");
            body.setCode("500");
            body.setDetail("申请医生代码RequestDoctor为空");
            response.setMsgBody(body);
            return response;
        }
        String applyDepartmentId = request.getMsgBody().getLabRequest().getRequestDept();
        applyDepartmentId=Tools.doKsdm(applyDepartmentId);
        labRequisition.setApplyDepartmentId(applyDepartmentId);
        //科室代码校验
        if (StringUtils.isEmpty(applyDepartmentId)) {
            body.setStatus("false");
            body.setCode("500");
            body.setDetail("申请科室代码RequestDept为空");
            response.setMsgBody(body);
            return response;
        }

        String toponymyID = request.getMsgBody().getLabRequest().getToponymyID();
        String diagnostic = "";
        String diagnostics = "";

        String zdxh = "";
        List<LabRequisitionRequest.MsgBody.LabRequest.Diagnoses> diagnosesList = request.getMsgBody().getLabRequest().getDiagnoses();
        //拼接多个诊断信息
        if(diagnosesList !=null){
            for(int i = 0;i<diagnosesList.size();i++){
                LabRequisitionRequest.MsgBody.LabRequest.Diagnoses diagnoses = diagnosesList.get(i);
                LabRequisitionRequest.MsgBody.LabRequest.Diagnose diagnose = diagnoses.getDiagnose();
                zdxh = diagnose.getDiagnoseCode();
                labRequisition.setZdxh(zdxh);
                diagnostic = diagnose.getDiagnoseName();
                if(diagnosesList.size()==1){
                    diagnostics = diagnostic;
                }else {
                    diagnostics += diagnostic+",";
                }
            }
            labRequisition.setDiagnostic(diagnostics);
        }
        String requesttime = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();//获取当前时间
        requesttime = formatter.format(curDate);
        if (applyTime.equals("")) {
            applyTime = requesttime;
        }
        labRequisition.setApplyTime(applyTime);
        String sql_sqd = "select * from L_LIS_SQD where doctrequestno = '" + applicationNo + "' and jgid = '" + jgid+"'";
        List<Map<String, Object>> list_sqd = jdbcTemplate.queryForList(sql_sqd);;
        log.info(sql_sqd);
        if (list_sqd.size() > 0) {
            body.setStatus("false");
            body.setCode("500");
            body.setDetail("申请单号为:" + applicationNo + "的申请单已存在,请核对传入的申请单号！");
            response.setMsgBody(body);
            return response;
        }
        List<LabRequisitionRequest.MsgBody.LabRequest.Items> itemsList = request.getMsgBody().getLabRequest().getItems();
        String sampleNo = "";
        String EXAMINAIMCODE = "";
        String EXAMINAIM = "";
        if(itemsList !=null){
            for(int i = 0;i<itemsList.size();i++) {
                LabRequisitionRequest.MsgBody.LabRequest.Items items = itemsList.get(i);
                LabRequisitionRequest.MsgBody.LabRequest.Item item = items.getItem();
                sampleNo = item.getSampleNo();
                String OrderId = item.getOrderId();
                labRequisitionMx.setOrderId(OrderId);
                String iSampleNo = item.getSampleNo();
                labRequisitionMx.setISampleNo(iSampleNo);
                String inspectionItemId = item.getItemCode();
                labRequisitionMx.setInspectionItemId(inspectionItemId);
                char ch = '_';
                int lastIndex = inspectionItemId.lastIndexOf(ch);
                if (lastIndex >= 0) {
                    inspectionItemId = inspectionItemId.substring(lastIndex + 1);
                }
                String specimenTypeId = "";
                String sam_sql = "select yblx from l_hyxm where hyid='" + inspectionItemId + "' and JGID = '" + jgid+"'";
                List<Map<String, Object>> samlist = jdbcTemplate.queryForList(sam_sql);
                log.info(sam_sql);
                for (int k = 0; k < samlist.size(); k++) {
                    Map<String, Object> sammap = samlist.get(k);
                    specimenTypeId = sammap.get("YBLX") + "";
                }
                String inspectionItemName = item.getItemName();
                labRequisitionMx.setInspectionItemName(inspectionItemName);

                String sampleTypeCode = item.getSampleTypeCode();
                labRequisitionMx.setSampleTypeCode(sampleTypeCode);
                if (null == sampleTypeCode || sampleTypeCode.trim().equalsIgnoreCase("")) {
                    sampleTypeCode = specimenTypeId;
                }
                String price = item.getItemPrice();
                labRequisitionMx.setDj(price);
                String number = item.getItemCount();
                labRequisitionMx.setSl(number);
                String FeeStatus = item.getFeeStatus();
                labRequisitionMx.setFeestatus(FeeStatus);
                String isFree = item.getCostFreeSign();
                labRequisitionMx.setIsFree(isFree);
                String InvoiceNo = item.getInvoiceNo();
                if (!StringUtils.isEmpty(InvoiceNo)) {
                    labRequisition.setFphm(InvoiceNo);
                }

                String sql_xm = "select HYID,YLXH,ZHPB,HYXM,XMLBA from L_HYXM where  hyid = '" + inspectionItemId + "' and jgid = '" + jgid+"'";
                List<Map<String, Object>> xmList = jdbcTemplate.queryForList(sql_xm);
                log.info(sql_xm);
                if (xmList.size() <= 0) {
                    body.setStatus("false");
                    body.setCode("500");
                    body.setDetail("机构id:" + jgid + ",hyid为:" + inspectionItemId + "的医嘱项目在表l_hyxm中未维护,请同步开单项目信息！");
                    response.setMsgBody(body);
                    return response;
                }
                String hyid = xmList.get(0).get("HYID")+"";
                String xmlba =xmList.get(0).get("XMLBA")+"";
                String izhpb1 = xmList.get(0).get("ZHPB")+"";
                int izhpb = Tools.ToInt(izhpb1);
                inspectionItemId =xmList.get(0).get("YLXH")+"";
                String orderId=sampleNo;
                labRequisition.setOrderId(orderId);
                if (EXAMINAIMCODE.equals(""))
                    EXAMINAIMCODE = hyid + ",";
                else
                    EXAMINAIMCODE = EXAMINAIMCODE + hyid + ",";
                if (EXAMINAIM.equals(""))
                    EXAMINAIM = inspectionItemName;
                else
                    EXAMINAIM = EXAMINAIM + "+" + inspectionItemName;
                labRequisition.setExaminaim(EXAMINAIM);
                labRequisition.setExaminaimcode(EXAMINAIMCODE);

//                List<HashMap> mxlist = new ArrayList<>();
                List<Map<String, Object>> list_mx1 = new ArrayList<>();
                if (izhpb > 0) //组合项目，得到明细
                {
                    getZhmx(jgid, hyid, jdbcTemplate, list_mx1);
                } else {
                    HashMap hyxmitem = new HashMap();
                    hyxmitem.put("DJ", price);
                    hyxmitem.put("SL", number);
                    hyxmitem.put("YLXH", inspectionItemId);
                    hyxmitem.put("HYXM", inspectionItemName);
                    hyxmitem.put("XMLBA", xmlba);
                    hyxmitem.put("HYID", hyid);
                    list_mx1.add(hyxmitem);
                }
                labRequisition.setFphm("");
                labRequisition.setToponymyId("");

                int resultSqd = labRequisitionService.addLabRequisition(labRequisition);
                //        labRequisition.setInpatientWardId("1");
                log.info("打印申请单入库数据："+labRequisition.toString());

                if (resultSqd < 0) {
                    body.setStatus("false");
                    body.setCode("500");
                    body.setDetail("插入申请单表失败！");
                    response.setMsgBody(body);
                    return response;
                }
                for(Map<String, Object> mxItem : list_mx1){
                    labRequisitionMx.setApplicationNo(applicationNo);
                    labRequisitionMx.setHyid(hyid);
                    labRequisitionMx.setInspectionItemName(inspectionItemName);
                    labRequisitionMx.setHyidmx(mxItem.get("HYID")+"");
                    labRequisitionMx.setYlxh(mxItem.get("YLXH")+"");
                    labRequisitionMx.setHyxm(mxItem.get("HYXM")+"");
                    labRequisitionMx.setDj( mxItem.get("DJ")+"");
                    labRequisitionMx.setSl( mxItem.get("SL")+"");
                    String iFeeStatus= "1";
                    if (FeeStatus.equals("") || FeeStatus.equals("0")) {
                        iFeeStatus = "1";
                    }
                    if (FeeStatus.equals("1"))
                    {
                        iFeeStatus="2";
                    }
                    labRequisitionMx.setFeestatus(iFeeStatus);

                    labRequisitionMx.setSampleTypeCode(sampleTypeCode);

                    labRequisitionMx.setJlxh_hihis(sampleNo);
                    if ((mxItem.get("XMLBA")+"") == null) {
                        labRequisitionMx.setXmlba(xmlba);
                    } else {
                        labRequisitionMx.setXmlba(mxItem.get("XMLBA")+"");
                    }
                    labRequisitionMx.setJgid(jgid);
                    labRequisitionMx.setOrderId(OrderId);
                    int resultSqdMx = labRequisitionService.addLabRequisitionMx(labRequisitionMx);
                    log.info("打印申请单明细入库数据："+labRequisitionMx.toString());
                    if (resultSqdMx < 0) {
                        body.setStatus("false");
                        body.setCode("500");
                        body.setDetail("插入申请单明细表失败！");
                        response.setMsgBody(body);
                        return response;
                    }
                }
            }
        }


        log.info("开单成功-------------------");
        body.setStatus("true");
        body.setCode("200");
        body.setDetail("成功");
        response.setMsgBody(body);
        return response;
    }
    //判断科室代码是否存在
    public static  Boolean getExistsByKsdm(Integer jgid, String ksdm,JdbcTemplate jdbcTemplate) {
        String sql = "select KSDM,KSMC from gy_ksdm where jgid = '"+jgid+"' and ksdm = '"+ksdm+"'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);;
        log.info(sql);
        if (list == null || list.size() <= 0) {
            return false;
        } else {
            return true;
        }
    }

    private Integer getZhmx(String jgid, String zhid,JdbcTemplate jdbcTemplate,List<Map<String, Object>> rlist) {
        Integer rownum = 0;
        if (rlist == null) {
            rlist = new ArrayList<>();
        }
        String sql = "select a.zhmxid as hyid,a.ZHPB,a.SL,a.DJ,(select ylxh from l_hyxm where hyid = a.zhmxid and jgid = a.jgid) as ylxh," +
                "(select hyxm from l_hyxm where hyid = a.zhmxid and jgid = a.jgid) as hyxm,b.XMLBA from l_hyxm b left join l_hyxm_zhmx a on a.jgid=b.jgid and a.hyid=b.hyid  where " +
                "a.hyid="+zhid+" and a.jgid='"+jgid+"'";
        List<Map<String, Object>> list_mx = jdbcTemplate.queryForList(sql);;
        log.info(sql);
        rownum = list_mx.size();
        if (list_mx.size() <= 0) {
            return rownum;
        }
        for (Map<String, Object> item : list_mx) {
            String zhpb2 = item.get("ZHPB")+"";
            int zhpb = Tools.ToInt(zhpb2);
            String zhmxid =item.get("HYID")+"";
            if (zhpb > 0) {
                if (getZhmx(jgid, zhmxid, jdbcTemplate, rlist) <= 0) {
                    rlist.add(item);
                }
            } else {
                rlist.add(item);
            }
        }
        return rownum;
    }
}
